<?php
/*
 * @Author: winner
 * @Date: 2022-04-23 23:56:06
 * @LastEditTime: 2022-04-27 11:21:25
 * @LastEditors: winner
 * @Description: 
 */
// +----------------------------------------------------------------------
// | ShopXO 国内领先企业级B2C免费开源电商系统
// +----------------------------------------------------------------------
// | Copyright (c) 2011~2099 http://shopxo.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( https://opensource.org/licenses/mit-license.php )
// +----------------------------------------------------------------------
// | Author: Devil
// +----------------------------------------------------------------------
namespace app\service;
use think\facade\Db;

/**
 * 子商户服务层
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-01T21:51:08+0800
 */
class MerchantService
{

    //增加子商户
    public static function MerchantAdd($params = [])
    {
        $ret =  Db::name('Merchant')->insertGetId($params);
        if ($ret <= 0) {
            return DataReturn('添加失败', -100);
        }
        return DataReturn('添加成功',0);
    }
    //获取子商户列表
    public static function MerchantList($params = [])
    {
        $where = empty($params['where']) ? [] : $params['where'];
        $field = empty($params['field']) ? '*' : $params['field'];
        $order_by = empty($params['order_by']) ? 'id desc' : trim($params['order_by']);
        $m = isset($params['m']) ? intval($params['m']) : 0;
        $n = isset($params['n']) ? intval($params['n']) : 10;

        // 获取用户列表
        $data = Db::name('Merchant')->where($where)->order($order_by)->field($field)->limit($m, $n)->select()->toArray();
        if(!empty($data)){
            foreach ($data as &$v) {
                // 时间
                if (array_key_exists('add_time', $v)) {
                    $v['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
                }
                if (array_key_exists('upd_time ', $v)) {
                    $v['upd_time '] = date('Y-m-d H:i:s', $v['upd_time']);
                }
            }
        }
        return DataReturn('处理成功', 0, $data);
    }

    /**
     * 子商户总数
     * @author   Devil
     * @blog     http://gong.gg/
     * @version  0.0.1
     * @datetime 2016-12-10T22:16:29+0800
     * @param    [array]          $where [条件]
     */
    public static function MerchantTotal($where)
    {
        return (int) Db::name('Merchant')->where($where)->count();
    }

    //根据参数获取银行所在省市县信息
    public  static function GetBankRegions($params = [])
    {
        // 数据参数
        $field = 'id,name,level,code';
        $where = empty($params['where']) ? [] : $params['where'];
        return Db::name('BankRegion')->where($where)->field($field)->select()->toArray();
    }

    //根据参数获取银行所在省市县信息
    public  static function GetBankRegion($params = [])
    {
        // 数据参数
        $sql = implode(',',$params);
        $field = 'id,name,level,code';
        $where = 'id in ('.$sql.') and is_enable = 1';
        $ret= Db::name('BankRegion')->where($where)->field($field)->select()->toArray();
        $ret = array_column($ret,Null,'id');
        $data = [];
        foreach ($params as $key => $value) {
            $data[$key] = $ret[$value];
        }
        return $data;
    }

    //获取银行省市县代码
    public static function RegionNode($params = [])
    {
         // 数据参数
        $field = empty($params['field']) ? 'id,name,level,code' : $params['field'];
        $where = empty($params['where']) ? [] : $params['where'];
        $order_by = empty($params['order_by']) ? 'sort asc,id asc' : trim($params['order_by']);

        // 基础条件
        $where['is_enable'] = 1;
        return Db::name('BankRegion')->where($where)->field($field)->order($order_by)->select()->toArray();
    }

    //获取银行代码
    public static function BankNode($params=[])
    {
        // 数据参数
        $field = 'id,name,code';
        $order_by = empty($params['order_by']) ? 'id asc' : trim($params['order_by']);
        return Db::name('BankCode')->where($params['where'])->field($field)->order($order_by)->select()->toArray();
    }

    public static function deviledtest($params = [])
    {
        // 数据参数
        $field = 'id ,trade_no,order_no,frozen_amount';
        return Db::name('Order')->where($params['where'])->field($field)->select()->toArray();
    }

    public  static function updateorder($params = [])
    {
        return Db::name('Order')->where(['order_no'=>$params['order_no']])->dec('frozen_amount',$params['amount'])->update();
    }

    public static function test()
    { 
        $a1 = [
            "parentMerchantNo"                   => "10034361159",
            "bankCity"                 => "330300", //银行城市编号
            "bankCode"                  => "313333460043", //银行代码
            "bankProvince"              => "330000", //银行省编号
            "cardNo"         => "6224490110090537", //银行卡信息
            "headBankCode"         => "JHYH", //银行代码
            "legalIdCard"         => "330324199601260014", //身份证号
            "legalName"         => "虞文强", //姓名
            "merLegalPhone"         => "13057877872", //银行卡预留手机号
            "mchntType" => "1",
            "merProvince"   => "330000",
            "merCity"       => "330300",
            "merDistrict"   => "330324",
            "merAddress"    => "永嘉县"
        ];

        try {
            $a1['sign'] = self::sign($a1);
            $a1['requestNo'] = 's12348';
            $a1['fileInfo'] = [
                [
                    'quaType' => 'HAND_IDCARD', //个人法人手持身份证
                    'quaUrl' => 'http://staticres.yeepay.com/jcptb-merchant-netinjt05/2022/04/26/merchant-1650960619850-6267a8eb3f6b0466821980314c29dcda-SLDYqgPkHLeYWjpudpKp.jpg',
                ],
                [
                    'quaType' => 'IDCARD_FRONT', //法人身份证正面
                    'quaUrl' => 'http://staticres.yeepay.com/jcptb-merchant-netinjt05/2022/04/26/merchant-1650960624080-6267a8ee8ebda234414327e9ad40ea5f-QctAPTCfjSJNteFdIexs.jpg',
                ],
                [
                    'quaType' => 'IDCARD_BACK', //法人身份证反面
                    'quaUrl' => 'http://staticres.yeepay.com/jcptb-merchant-netinjt05/2022/04/26/merchant-1650960628555-6267a8f30340c589684460aaa6a908a8-ljEOzhBVkACNfKxFakwj.jpg',
                ],
                [
                    'quaType' => 'SETTLE_BANKCARD', //结算银行卡
                    'quaUrl' => 'http://staticres.yeepay.com/jcptb-merchant-netinjt05/2022/04/26/merchant-1650960630696-6267a8f5b887f584307884a8782a4bda-jNkSeTcSdJLeoFVydHVZ.jpg',
                ]
            ];
        } catch (\Exception $e) {
            print_r($e->getMessage());
        }
        $requestUrl = "/api/yoppro/merchant/addreq";
        $jsonStr = json_encode($a1, JSON_UNESCAPED_UNICODE);

        $res = self::httpJson($requestUrl, $jsonStr);
        print_r($res);
    }

    public static function in($params = [])
    {
        //主商户号
        $config = Db::name('Config')->where(['only_tag'=> 'common_tgpay_parentmerno'])->field('value')->find();
        $data = [
            "parentMerchantNo" => $config['value'],
            "bankCity" => $params['bank_city'], //银行城市编号
            "bankCode"  => "313333460043",//$params['bank_code'], //银行编号，通过接口获取
            "bankProvince" => $params['bank_province'], //银行省编号
            "cardNo"=> $params['card_no'], //银行卡号
            "headBankCode"=> $params['head_bankno'], //银行代码
            "legalIdCard"=> $params['legal_idcard'], //身份证号
            "legalName"=> $params['legal_name'], //姓名
            "merLegalPhone"=> $params['mobile'], //银行卡预留手机号
            "mchntType" => $params['mchnt_type'],//入网类型
            "merProvince"=> $params['mer_province'],//商户所在地省份编号
            "merCity"=> $params['mer_city'],//商户所在地市编号
            "merDistrict"=> $params['mer_district'],//商户所在地县区编号
            "merAddress"=> $params['mer_address']//商户所在地县区名称
        ];
        try {
            $a1['sign'] = self::sign($data);
            $a1['requestNo'] = 'rfl'.time();
            $a1['fileInfo'] = [
                [
                    'quaType' => 'IDCARD_FRONT', //法人身份证正面
                    'quaUrl' => $params['idcard_front'],
                ],
                [
                    'quaType' => 'IDCARD_BACK', //法人身份证反面
                    'quaUrl' => $params['idcard_back'],
                ],
                [
                    'quaType' => 'SETTLE_BANKCARD', //结算银行卡
                    'quaUrl' => $params['settle_bankcard'],
                ],
                [
                    'quaType' => 'HAND_IDCARD', //个人法人手持身份证
                    'quaUrl' => $params['hand_idcard'],
                ]
            ];
        } catch (\Exception $e) {
            print_r($e->getMessage());
        }
        $requestUrl = "/api/yoppro/merchant/addreq";
        $jsonStr = json_encode($a1, JSON_UNESCAPED_UNICODE);

        $res = self::httpJson($requestUrl, $jsonStr);
        return $res;
    }

    //上传证件图片
    public static function upload(array $params = [])
    {
        $a = ["picName"=> $params['imgname']];
        $a['sign'] = self::sign($a);
        $a['picUrl'] = $params['img_url'];
        $requestUrl = "/api/yoppro/file/upload";
        $jsonStr = json_encode($a, JSON_UNESCAPED_UNICODE);
        $res = self::httpJson($requestUrl, $jsonStr);
        return $res;
    }


    //获取银行编号
    public static function code($params = [])
    {
        $a = [ "headBankNo" => $params['head_bankno'],
            "bankProvinceNo"=> $params['bank_province'],
            "bankCityNo"=> $params['bank_city']
        ];
        $a['sign'] = self::sign($a);
        $requestUrl = "/api/yoppro/bank/branch";
        $jsonStr = json_encode($a, JSON_UNESCAPED_UNICODE);
        $res = self::httpJson($requestUrl, $jsonStr);
        return $res;
    }

    //生成签名
    private static function sign($params)
    {
        //获取入网秘钥
        $key = Db::name('Config')->where(['only_tag' => 'common_tgpay_merchantkey'])->field('value')->find();
        ksort($params);
        $str = '';
        foreach ($params as $k => $v) {
            $str .= ($k . '=' . $v . '&');
        }
        $str = substr($str, 0, -1);
        $str .= '&key=' . $key['value'];
        $sign = strtoupper(md5($str));
        return $sign;
    }


    private static function httpJson($url, $jsonStr)
    {
        try {
            // $url = 'https://tgpay.833006.net' .$url;
            $url = 'http://agency.yltg.com.cn' . $url;

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt(
                $ch,
                CURLOPT_HTTPHEADER,
                array(
                    'Content-Type: application/json; charset=utf-8',
                    'Content-Length: ' . strlen($jsonStr)
                )
            );
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            return json_decode($response, true);
            return array($httpCode, json_decode($response, true));
        } catch (\Exception $e) {
        }
        return [];
    }

    /**
     * [HttpRequestGet get请求]
     * @param    [string]           $url [url地址]
     * @return   [array]                 [返回数据]
     * @author   Devil
     * @blog     http://gong.gg/
     * @version  1.0.0
     * @datetime 2018-01-03T19:21:38+0800
     */
    private static function HttpRequestGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);
        return json_decode($res, true);
    }

    /**
     * [HttpRequestPost curl模拟post]
     * @param    [string]   $url        [请求地址]
     * @param    [array]    $data       [发送的post数据]
     * @param    [array]    $is_parsing [是否需要解析数据]
     * @return   [array]                [返回的数据]
     * @author   Devil
     * @blog     http://gong.gg/
     * @version  1.0.0
     * @datetime 2017-09-25T09:10:46+0800
     */
    private static function HttpRequestPost($url, $data, $is_parsing = true)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_POST, true);

        $res = curl_exec($curl);
        if ($is_parsing === true) {
            return json_decode($res, true);
        }
        return $res;
    }

}
?>